/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.db.examples;

import java.sql.ResultSet;
import java.sql.SQLException;
import fschmidt.db.DbObject;
import fschmidt.db.DbRecord;
import fschmidt.db.DbKey;
import fschmidt.db.LongKey;
import fschmidt.db.DbFinder;
import fschmidt.db.DbDatabase;
import fschmidt.db.DbTable;
import fschmidt.db.DbObjectFactory;


public class Example implements DbObject<LongKey,Example> {
	static final String url = "jdbc:mysql://localhost/talk";
	static final String user = "";
	static final String password = "";
	static DbDatabase db = DbFinder.getDatabase(url,user,password);

	private final DbRecord<LongKey,Example> record;
	private String text;

	private Example(LongKey key,ResultSet rs)
		throws SQLException
	{
		record = table.newRecord(this,key);
		text = rs.getString("text");
	}

	public Example(String text) {
		record = table.newRecord(this);
		this.text = text;
	}

	public DbRecord<LongKey,Example> getDbRecord() {
		return record;
	}

	public long getId() {
		return record.getPrimaryKey().value();
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
		record.fields().put("text",text);
	}

	static DbTable<LongKey,Example> table = db.newTable( "example", db.newIdentityLongKeySetter("example_id"),
		new DbObjectFactory<LongKey,Example>() {
			public Example makeDbObject(LongKey key,ResultSet rs,String tableName)
				throws SQLException
			{
				return new Example(key,rs);
			}
		}
	);

	public static Example findExample(long id) {
		return table.findByPrimaryKey(new LongKey(id));
	}

	public static void main(String[] args) throws Exception {
		Example example = new Example("hello world");
		example.getDbRecord().insert();
		long id = example.getId();

		example = findExample(id);
		System.out.println(example.getText());
	}
}
